/**
 * 省市区三级级联插件
 */
import React, {Component} from 'react';
import {connect} from 'dva';
import {Cascader} from 'antd';
import commonService from '../../services/commonService';

class AreaPicker extends Component {
  state = {
    options: []
  };

  componentDidMount() {
    let t = this;
    this.getArea().then((data) => {
      t.setState({
        options: data
      })
    });
  };

  //获取行政区
  getArea = async (keywords) => {
    const params = {
      key: '6a7f8dfb2665080da730703a86ca6ff3',
      subdistrict: 1,
      keywords
    };
    const data = await commonService.getDistrict(params);
    console.log(data, '行政区结果data');
    return data.ret.districts[0].districts.length>0&&data.ret.districts[0].districts.map(item => ({
      label: item.name,
      value: item.level==='street'?item.name:item.adcode,
      level: item.level,
      isLeaf: item.level==='street'||false
    }));
  };

  //行政区框动态加载
  loadData = (selectedOptions) => {
    let t = this;
    const targetOption = selectedOptions[selectedOptions.length - 1];

    if (targetOption.level !== 'street'){
      targetOption.loading = true;
      this.getArea(targetOption.value).then((data) => {
        targetOption.loading = false;
        targetOption.children = data;
        targetOption.isLeaf = !data;
        t.setState({
          options: [...this.state.options],
        });
      });
    }

  };

  render() {
    let t = this;
    const {options} = t.state;
    const loadData = t.props.options?'':{loadData:this.loadData};
    return (
      <Cascader
        options={t.props.options||options}
        size={t.props.size}
        changeOnSelect={t.props.changeOnSelect}
        allowClear={t.props.allowClear===false?false:true}
        onChange={t.props.onChange}
        {...loadData}
        placeholder="请选择"/>
    )
  }
}
function mapStateToProps(state) {
  return {};
}
export default connect(mapStateToProps)(AreaPicker);
